package znbkBkfx.BKFX_TLTK;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.znbk.znbklibrary.base.AnswerViewPagerAdapter;
import com.example.znbk.znbklibrary.base.BaseFragment;
import com.example.znbk.znbklibrary.util.LancooUtils;
import com.example.znbk.znbklibrary.voicePlayer.VoicePlayer;
import com.example.znbk.znbklibrary.widget.ScaleButton;
import com.lancoo.znbkxx.R;

import java.util.ArrayList;

import znbkBkfx.AboutCountDowm.CountDownView;
import znbkBkfx.BkfxActivity;
import znbkBkfx.GetBkfxJson.BkfxPaperEntity;

@SuppressLint("ValidFragment")
public class BkfxTltkFragment extends BaseFragment {

    private String AudioPath = "";
    private void getEntityInfor(){
        AudioPath = bkfxPaperEntity.getQuesList().get(quesIndex).getAudioList().get(0).getPath();
    }

    private BkfxPaperEntity bkfxPaperEntity;
    private int quesIndex = -1;
    private CallBackFragmentTltk callBackFragmentTltk;
    public BkfxTltkFragment(BkfxPaperEntity bkfxPaperEntity, final int quesIndex,CallBackFragmentTltk callBackFragmentTltk){
        this.bkfxPaperEntity = bkfxPaperEntity;
        this.quesIndex = quesIndex;
        this.callBackFragmentTltk = callBackFragmentTltk;
        getEntityInfor();
    }

    @Override
    protected int createLayout() {
        return R.layout.bkfx_fragment_tltk;
    }

    private ImageButton mIBtnPlayPause;//音频控制按钮
    private SeekBar mSbMusicProgress;//音频进度条
    private TextView mTvMusicTime;//播放时间点
    private WebView mWvQuesBody;

    private ViewPager mVpAnswer;
    private ArrayList<View> list;
    public AnswerViewPagerAdapter mAnswerViewPagerAdapter;

    private RelativeLayout mRlMyBrowseBg;
    private CountDownView mCdvMyBrowse;

    private RelativeLayout mRlControlView;
    private ScaleButton mSBtnSubmit;

    public boolean isVoicePlayingEnd = false;

    private LinearLayout mLlResultStuScore;

    @Override
    protected void initView(View view) {
        //显示播放器
        mIBtnPlayPause = view.findViewById(R.id.ibtn_audioIcon);
        mSbMusicProgress = view.findViewById(R.id.sb_musicProgress);
        mTvMusicTime = view.findViewById(R.id.tv_musicTime);
        mWvQuesBody = view.findViewById(R.id.wv_quesBody);
        mWvQuesBody.setBackgroundColor(0); // 设置背景色
        String QuesBodyAsk  = bkfxPaperEntity.getQuesList().get(quesIndex).getChildList().get(0).getSubChildList().get(0).getSubChildAsk();
        mWvQuesBody.loadData(QuesBodyAsk+"</br>", "text/html", "utf-8");

        mVoicePlayer = new VoicePlayer(mSbMusicProgress, AudioPath, mTvMusicTime, mIBtnPlayPause,
                false, true, false, new VoicePlayer.FinishPlay() {
            @Override
            public void onFinishPlay() {
                isVoicePlayingEnd = true;
                //音频播放结束，点亮录音按钮（此处需要刷新界面）
                list = new ArrayList<>();
                list.clear();
                RecyclerView mRvAnswer = new RecyclerView(getActivity());
                mRvAnswer.setLayoutManager(new LinearLayoutManager(getActivity()));//必须先设置LayoutManager
                BkfxTltkAnswerAdapter mAnswerAdapter = new BkfxTltkAnswerAdapter(getActivity(),
                        bkfxPaperEntity,quesIndex,isVoicePlayingEnd);
                mAnswerAdapter.setHasStableIds(true);
                mRvAnswer.setAdapter(mAnswerAdapter);
                int ItemSize  = bkfxPaperEntity.getQuesList().get(quesIndex).getTotalItemCount();
                mRvAnswer.setItemViewCacheSize(ItemSize);
                list.add(mRvAnswer);
                mAnswerViewPagerAdapter = new AnswerViewPagerAdapter(list);
                mVpAnswer.setAdapter(mAnswerViewPagerAdapter);
            }
        });
        int State = bkfxPaperEntity.getState();
        if(State==2||State==3){
            mVoicePlayer.setBtnPlayClickAble(true);
        }

        //显示TlxzAnswer内容
        //显示Answer信息
        mVpAnswer = view.findViewById(R.id.vp_answerTltk);
        list = new ArrayList<>();
        list.clear();
        RecyclerView mRvAnswer = new RecyclerView(getActivity());
        mRvAnswer.setLayoutManager(new LinearLayoutManager(getActivity()));//必须先设置LayoutManager
        BkfxTltkAnswerAdapter mAnswerAdapter = new BkfxTltkAnswerAdapter(getActivity(),
                bkfxPaperEntity,quesIndex,isVoicePlayingEnd);
        mAnswerAdapter.setHasStableIds(true);
        mRvAnswer.setAdapter(mAnswerAdapter);
        int ItemSize  = bkfxPaperEntity.getQuesList().get(quesIndex).getTotalItemCount();
        mRvAnswer.setItemViewCacheSize(ItemSize);
        list.add(mRvAnswer);
        mAnswerViewPagerAdapter = new AnswerViewPagerAdapter(list);
        mVpAnswer.setAdapter(mAnswerViewPagerAdapter);
        mVpAnswer.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                bkfxPaperEntity.getPaperAnswer().get(quesIndex).setCurrentSubChildAnswerIndex(i);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        //显示提交按钮
        mRlControlView = view.findViewById(R.id.rl_controlView);
        mSBtnSubmit  = view.findViewById(R.id.sbtn_submit);
        mSBtnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bkfxPaperEntity.getPaperAnswer().get(quesIndex).setSubmitState(2);
                hideSBtnSubmit();
            }
        });
        int SubmitState = bkfxPaperEntity.getPaperAnswer().get(quesIndex).getSubmitState();
        if(SubmitState==2){
            mRlControlView.setVisibility(View.GONE);
        }else {
            showSBtnSubmit();
        }

        //显示浏览倒计时
        mRlMyBrowseBg = view.findViewById(R.id.rl_myBrowseBg);
        mCdvMyBrowse =  view.findViewById(R.id.cdv_myBrowse);
        mCdvMyBrowse.setCountdownTime(5);
        mCdvMyBrowse.setRingWidth(12);
        mCdvMyBrowse.setAddCountDownListener(new CountDownView.OnCountDownFinishListener() {
            @Override
            public void countDownFinished() {
                LancooUtils.showShort(getActivity(),"倒计时结束");
                hideBrowseView();
                play();
                bkfxPaperEntity.getPaperAnswer().get(quesIndex).setSubmitState(1);
            }
        });
        mCdvMyBrowse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mCdvMyBrowse.pauseCountDown();

                bkfxPaperEntity.getPaperAnswer().get(quesIndex).setSubmitState(1);
                hideBrowseView();//开启隐藏浏览view动画
                play();
            }
        });

        //学生作答得分
        mLlResultStuScore = view.findViewById(R.id.ll_resultStuScore);

    }

    @SuppressLint("NewApi")
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        int SubmitState = bkfxPaperEntity.getPaperAnswer().get(quesIndex).getSubmitState();

        if(isVisibleToUser){
            Log.e("setUserVisibleHint","================AnswerState===================="+SubmitState);
            if(SubmitState==0) {
                final Handler mH = new Handler();
                mH.post(new Runnable() {
                    @Override
                    public void run() {

                        if(mCdvMyBrowse!=null) {
                            if (mCdvMyBrowse.isCountDownRunning()) {
                                mCdvMyBrowse.resumeCountDown();
                            } else {
                                showBrowseView();
                                mCdvMyBrowse.startCountDown();
                            }
                            mH.removeCallbacks(this);
                        }else{
                            mH.post(this);
                        }

                    }
                });
            }else if(SubmitState==1){
                if(!isVoicePlayingEnd) {
                    play();
                }
            }else if(SubmitState==2){
                pause();
            }

        }else{
            pause();
            if(mCdvMyBrowse!=null) {
                mCdvMyBrowse.pauseCountDown();
            }
        }

    }

    private void showBrowseView(){
        if(mRlMyBrowseBg.getVisibility()==View.GONE) {
            ObjectAnimator translationY = ObjectAnimator.ofFloat(mRlMyBrowseBg, View.TRANSLATION_Y, 300f, 0f);
            AnimatorSet setShow = new AnimatorSet();
            setShow.playTogether(translationY);
            setShow.setDuration(300);
            setShow.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                    mRlMyBrowseBg.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationEnd(Animator animation) {

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            setShow.start();
        }
    }
    private void hideBrowseView(){
        if(mRlMyBrowseBg.getVisibility()==View.VISIBLE) {
            ObjectAnimator translationY = ObjectAnimator.ofFloat(mRlMyBrowseBg, View.TRANSLATION_Y, 0f, 300f);
            AnimatorSet setShow = new AnimatorSet();
            setShow.playTogether(translationY);
            setShow.setDuration(300);
            setShow.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    mRlMyBrowseBg.setVisibility(View.GONE);
                    list = new ArrayList<>();
                    list.clear();
                    RecyclerView mRvAnswer = new RecyclerView(getActivity());
                    mRvAnswer.setLayoutManager(new LinearLayoutManager(getActivity()));//必须先设置LayoutManager
                    BkfxTltkAnswerAdapter mAnswerAdapter = new BkfxTltkAnswerAdapter(getActivity(),
                            bkfxPaperEntity,quesIndex,isVoicePlayingEnd);
                    mAnswerAdapter.setHasStableIds(true);
                    mRvAnswer.setAdapter(mAnswerAdapter);
                    int ItemSize  = bkfxPaperEntity.getQuesList().get(quesIndex).getTotalItemCount();
                    mRvAnswer.setItemViewCacheSize(ItemSize);
                    list.add(mRvAnswer);
                    mAnswerViewPagerAdapter = new AnswerViewPagerAdapter(list);
                    mVpAnswer.setAdapter(mAnswerViewPagerAdapter);
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            setShow.start();
        }
    }


    private void doSubmitRefresh(){
        list.clear();
        RecyclerView mRvAnswer = new RecyclerView(getActivity());
        mRvAnswer.setLayoutManager(new LinearLayoutManager(getActivity()));//必须先设置LayoutManager
        BkfxTltkAnswerAdapter mAnswerAdapter = new BkfxTltkAnswerAdapter(getActivity(), bkfxPaperEntity, quesIndex,isVoicePlayingEnd);
        mAnswerAdapter.setHasStableIds(true);
        mRvAnswer.setAdapter(mAnswerAdapter);
        int ItemSize  = bkfxPaperEntity.getQuesList().get(quesIndex).getTotalItemCount();
        mRvAnswer.setItemViewCacheSize(ItemSize);
        list.add(mRvAnswer);
        mAnswerViewPagerAdapter = new AnswerViewPagerAdapter(list);
        mVpAnswer.setAdapter(mAnswerViewPagerAdapter);

        int AnsweredCount=0;
        int AnsweredCountTrue=0;
        int SubChildItemSize = bkfxPaperEntity.getQuesList().get(quesIndex).getChildList().get(0).
                getSubChildList().get(0).getSubChildItem().size();
        for(int i=0;i<SubChildItemSize;i++){
            String StuAnswer =  bkfxPaperEntity.getPaperAnswer().get(quesIndex).getChildList().
                    get(0).getSubChildList().get(0).getSubChildItem().get(i).getStuAnswer();
            if(!StuAnswer.equals("")){
                AnsweredCount = AnsweredCount+1;
            }

            String ItemAnswer =  bkfxPaperEntity.getQuesList().get(quesIndex).getChildList().
                    get(0).getSubChildList().get(0).getSubChildItem().get(i).getItemAnswer();
            if(ItemAnswer.equals(StuAnswer)){
                AnsweredCountTrue = AnsweredCountTrue+1;
            }
        }
        //若作答完成则显示答案，记录作答状态，否则亦然
        bkfxPaperEntity.getPaperAnswer().get(quesIndex).setSubmitState(2);

        double EachScore = 0;
        String QuesList_QuesID = bkfxPaperEntity.getQuesList().get(quesIndex).getQuesID();
        int PaperQuesSize = bkfxPaperEntity.getPaperQues().size();
        for(int i=0;i<PaperQuesSize;i++) {
            int PaperQues_QuesListSize = bkfxPaperEntity.getPaperQues().get(quesIndex).getQuesList().size();
            for (int j = 0; j < PaperQues_QuesListSize; j++) {
                String PaperQues_QuesID = bkfxPaperEntity.getPaperQues().get(quesIndex).getQuesList().get(j).getQuesID();
                if (QuesList_QuesID.equals(PaperQues_QuesID)) {
                    EachScore = bkfxPaperEntity.getPaperQues().get(quesIndex).getEachScore();
                    break;
                }
            }
        }
        double ResultStuScore = AnsweredCountTrue*EachScore;
        showResultStuScore(ResultStuScore);
        callBackFragmentTltk.submitKgtQuesAnswer();

    }


    private void showSBtnSubmit(){

        ObjectAnimator translationY1 = ObjectAnimator.ofFloat(mRlControlView, View.TRANSLATION_Y, 300f, 0f);
        ObjectAnimator translationY2 = ObjectAnimator.ofFloat(mSBtnSubmit, View.TRANSLATION_Y, 300f, 0f);
        AnimatorSet setShow = new AnimatorSet();
        setShow.playTogether(translationY1,translationY2);
        setShow.setDuration(800);
        setShow.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                mRlControlView.setVisibility(View.VISIBLE);
                mSBtnSubmit.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animator animation) {

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        setShow.start();
    }

    private void hideSBtnSubmit(){
        if(mSBtnSubmit.getVisibility()==View.VISIBLE) {
            ObjectAnimator translationY1 = ObjectAnimator.ofFloat(mRlControlView, View.TRANSLATION_Y, 0f, 300f);
            ObjectAnimator translationY2 = ObjectAnimator.ofFloat(mSBtnSubmit, View.TRANSLATION_Y, 0f, 300f);
            AnimatorSet setShow = new AnimatorSet();
            setShow.playTogether(translationY1,translationY2);
            setShow.setDuration(800);
            setShow.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    mRlControlView.setVisibility(View.GONE);
                    doSubmitRefresh();
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            setShow.start();
        }
    }

    public interface CallBackFragmentTltk {
        void pageMoveNext();
        void submitKgtQuesAnswer();
    }

    private void showResultStuScore(double stuScore){

        String strStuScore = String.valueOf(stuScore);
        if (strStuScore.contains("."))
        {
            String [] newStuScore = strStuScore.split("\\.");
            String front_stuScore = newStuScore[0];
            if(Integer.valueOf(front_stuScore)>=0 && Integer.valueOf(front_stuScore)<=9){
                drawStuScore(front_stuScore);
            }else{
                String str_front_stuScore_0 = front_stuScore.substring(0,1);
                drawStuScore(str_front_stuScore_0);
                String str_front_stuScore_1 = front_stuScore.substring(1,2);
                drawStuScore(str_front_stuScore_1);
            }
            String after_stuScore = newStuScore[1];
            if(Integer.valueOf(after_stuScore)>0){
                ImageView mIv_point = new ImageView(getActivity());
                mIv_point.setImageResource(R.mipmap.stu_score_point);
                mLlResultStuScore.addView(mIv_point);

                ImageView mIv_5 = new ImageView(getActivity());
                mIv_5.setImageResource(R.mipmap.stu_score_5);
                mLlResultStuScore.addView(mIv_5);

            }
        }

        ObjectAnimator translationXShow =  ObjectAnimator.ofFloat(mLlResultStuScore,View.TRANSLATION_X,500f,0f);
        ObjectAnimator alphaShow =  ObjectAnimator.ofFloat(mLlResultStuScore,View.ALPHA,0.6f,1.0f);
        AnimatorSet setShow = new AnimatorSet();
        setShow.playTogether(translationXShow,alphaShow);
        setShow.setInterpolator(new DecelerateInterpolator());
        setShow.setDuration(1600);
        setShow.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                mLlResultStuScore.setVisibility(View.VISIBLE);
                BkfxActivity.mVpBkfx.setScrollble(false);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mLlResultStuScore.setVisibility(View.GONE);
                callBackFragmentTltk.pageMoveNext();
                BkfxActivity.mVpBkfx.setScrollble(true);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        setShow.start();

        Log.e("showResultStuScore","=======tlxz=========stuScore==============="+stuScore);

    }

    private void drawStuScore(String score){
        if(score.equals("0")){
            ImageView mIv_0 = new ImageView(getActivity());
            mIv_0.setImageResource(R.mipmap.stu_score_0);
            mLlResultStuScore.addView(mIv_0);
        }else if(score.equals("1")){
            ImageView mIv_1 = new ImageView(getActivity());
            mIv_1.setImageResource(R.mipmap.stu_score_1);
            mLlResultStuScore.addView(mIv_1);
        }else if(score.equals("2")){
            ImageView mIv_2 = new ImageView(getActivity());
            mIv_2.setImageResource(R.mipmap.stu_score_2);
            mLlResultStuScore.addView(mIv_2);
        }else if(score.equals("3")){
            ImageView mIv_3 = new ImageView(getActivity());
            mIv_3.setImageResource(R.mipmap.stu_score_3);
            mLlResultStuScore.addView(mIv_3);
        }else if(score.equals("4")){
            ImageView mIv_4 = new ImageView(getActivity());
            mIv_4.setImageResource(R.mipmap.stu_score_4);
            mLlResultStuScore.addView(mIv_4);
        }else if(score.equals("5")){
            ImageView mIv_5 = new ImageView(getActivity());
            mIv_5.setImageResource(R.mipmap.stu_score_5);
            mLlResultStuScore.addView(mIv_5);
        }else if(score.equals("6")){
            ImageView mIv_6 = new ImageView(getActivity());
            mIv_6.setImageResource(R.mipmap.stu_score_6);
            mLlResultStuScore.addView(mIv_6);
        }else if(score.equals("7")){
            ImageView mIv_7 = new ImageView(getActivity());
            mIv_7.setImageResource(R.mipmap.stu_score_7);
            mLlResultStuScore.addView(mIv_7);
        }else if(score.equals("8")){
            ImageView mIv_8 = new ImageView(getActivity());
            mIv_8.setImageResource(R.mipmap.stu_score_8);
            mLlResultStuScore.addView(mIv_8);
        }else if(score.equals("9")){
            ImageView mIv_9 = new ImageView(getActivity());
            mIv_9.setImageResource(R.mipmap.stu_score_9);
            mLlResultStuScore.addView(mIv_9);
        }
    }

}
